package mysql

import (
	"gitee.com/guolianyu/kit/skit/third_party/config"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

func New(c *config.Database, l logger.Interface) (*gorm.DB, error) {
	db, err := gorm.Open(mysql.New(mysql.Config{
		DriverName: c.Driver,
		DSN:        c.Source,
	}), &gorm.Config{
		Logger:                                   l,
		SkipDefaultTransaction:                   true,
		DisableForeignKeyConstraintWhenMigrating: true,
	})

	if err != nil {
		return nil, err
	}

	sqlDB, err := db.DB()
	if err != nil {
		return nil, err
	}

	if c.ConnMaxIdleTime.Seconds > 0 {
		sqlDB.SetConnMaxIdleTime(c.ConnMaxIdleTime.AsDuration())
	}

	if c.ConnMaxLeftTime.Seconds > 0 {
		sqlDB.SetConnMaxLifetime(c.ConnMaxLeftTime.AsDuration())
	}

	if c.MaxIdleConn > 0 {
		sqlDB.SetMaxIdleConns(int(c.MaxIdleConn))
	}

	if c.MaxOpenConn > 0 {
		sqlDB.SetMaxOpenConns(int(c.MaxOpenConn))
	}
	return db, nil
}
